<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/11
 * Time: 10:28
 */

namespace Kordar\Tree;

/**
 * Class Classification
 * @package yak\libs\tree
 * 树、森林 => 二叉树
 */
class Classification
{
    private $groupHeap;

    public function __construct($data)
    {
        $this->groupHeap = (new Group())->minHeapArr($data);
    }

    public function getGroups()
    {
        return $this->groupHeap;
    }

    private function hasGroupChild($key)
    {
        return isset($this->groupHeap[$key]);
    }

    public function binaryTree($rootNumber = 0)
    {
        return $this->groupToBinaryTree($rootNumber);
    }

    private function insertBinaryRightNode(array $nodes)
    {
        $node = array_shift($nodes);
        if (!empty($nodes)) {
            $node->right = $this->insertBinaryRightNode($nodes);
        }
        if ($this->hasGroupChild($node->data['id'])) {
            $node->left = $this->groupToBinaryTree($node->data['id']);
        }
        return $node;
    }

    private function groupToBinaryTree($number)
    {
        /**
         * @var $node BinaryNode
         */
        $nodes = (array)$this->groupHeap[$number];
        $node = array_shift($nodes);
        if (!empty($nodes)) {
            $node->right = $this->insertBinaryRightNode($nodes);
        }
        if ($this->hasGroupChild($node->data['id'])) {
            $node->left = $this->groupToBinaryTree($node->data['id']);
        }
        return $node;
    }

}